<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-05-07
 * Time: 15:32
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Log;

class Callback extends Controller
{

    /**
     * 空操作
     */
    public function _empty(){
        if($this->check_admin_login()){
            $this->redirect('admin/Index/index');
        }else{
            $this->redirect('admin/login');
        }
    }

    /**
     * 淘宝授权回调
     */
    public function tbauth()
    {
        $code = input('param.code', '');
        $postfields = array('grant_type' => 'authorization_code',
            'client_id' => '24741714',
            'client_secret' => 'f2f5a9c7417b0ab85fbda53989b3b5ec',
            'code' => $code,
            'redirect_uri' => 'https://mina.anymean.com/admin/');
        $url = 'https://oauth.taobao.com/token';
        $post_data = '';
        foreach ($postfields as $key => $value) {
            $post_data .= "$key=" . urlencode($value) . "&";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        //指定post数据
        curl_setopt($ch, CURLOPT_POST, true);
        //添加变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data, 0, -1));
        $output = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpStatusCode == 200) {
            $info = json_decode($output, true);
            Log::info($info);
            $auth_info = Db::table('yf_tbauth')->where(['taobao_user_id' => $info['taobao_user_id']])->find();
            if (!empty($auth_info)) {
                $info['id'] = $auth_info['id'];
                $flag = Db::table('yf_tbauth')->update($info);
            } else {
                $data['w1_expires_in'] = $info['w1_expires_in'];
                $data['refresh_token_valid_time'] = $info['refresh_token_valid_time'];
                $data['taobao_user_nick'] = $info['taobao_user_nick'];
                $data['re_expires_in'] = $info['re_expires_in'];
                $data['expire_time'] = $info['expire_time'];
                $data['token_type'] = $info['token_type'];
                $data['access_token'] = $info['access_token'];
                $data['taobao_open_uid'] = $info['taobao_open_uid'];
                $data['refresh_token'] = $info['refresh_token'];
                $data['r1_expires_in'] = $info['r1_expires_in'];
                $data['r2_expires_in'] = $info['r2_expires_in'];
                $data['taobao_user_id'] = $info['taobao_user_id'];
                $flag = Db::table('yf_tbauth')->insert($data);
            }
            if ($flag) {
                $this->redirect('https://mina.anymean.com/admin/');
            }
        }
    }
}